package com.danhuang.cloud.danhuangdaily.interceptor;



import cn.hutool.json.JSONUtil;
import com.danhuang.cloud.danhuangcore.annotation.DanHuang;
import com.danhuang.cloud.danhuangcore.constant.OpenIdConstant;
import com.danhuang.cloud.danhuangcore.constant.ResConstant;
import com.danhuang.cloud.danhuangcore.model.DhRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


@Slf4j
public class DcdInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            DanHuang danHuang =  method.getAnnotation(DanHuang.class);
            if (danHuang != null) {
                String openId = request.getHeader("openId");
                if(!OpenIdConstant.check(openId)){
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json");
                    response.getWriter().println(JSONUtil.toJsonStr(DhRes.fail(ResConstant.NO_PERMISSION_CODE)));
                    response.getWriter().flush();
                    return false;
                }
            }
        }
        return true;
    }

}
